local desc_huanhua = [[
  # 幻化之战简介

  ---

  ## 身份说明

  游戏由2~10名玩家进行，玩家们各自为战，力求活到最后！

  ---

  ## 游戏目标
  游戏开始玩家会获得保护目标和击杀目标
  
  杀死所有其他角色，存活到最后的角色为第一名。保护你的保护目标并击杀击杀目标以获得优势


  ---


  ## 击杀奖励
  
  一名角色死亡时，杀死其的角色摸三张牌。
  若死亡角色为其他角色的保护目标，则该角色失去1点体力上限和体力，同时随机失去1个技能
  若死亡角色为其他角色的击杀目标，则该角色增加1点体力上限和体力，同时随机获得死亡角色的1个技能

  ---

  ## 新生

  所有角色只能保留1个技能。并且所有的角色的体力上限、体力值会被调整到4点、护甲会归零。

  ---

  ## 黑名单

  奋勇（SP夏侯惇）、绝境（高达一号）、仁德（刘备）

  ---

  ## 幻化

  每轮开始时，存活角色各自选择一项：1. 进行一次幻化（随机观看3个技能，选择其中1个技能获得）。2. 摸两张牌。

  ---

  ## 天劫

  每轮结束时，若当前轮数大于3，存活角色各自失去1点体力，减1点体力上限。该效果每回合都会提高

  ---

  注：目前来看AI无法正常幻化

]]

Huanhuaengine = require "packages/huanhua/Huanhuaengine"


  --技能给予
local addSkills = function(room, player, skillName)
  local skill = Fk.skills[skillName]
  if skill.lordSkill and (player.role ~= "lord" or #room.players < 5) then
    return
  end
  room:handleAddLoseSkills(player, skillName, nil, false)
end

  --获取技能
local function huanhua_Newskill(room)
  local players = room.alive_players
  local n = #players
  local ChosenGenerals = {}
  for _, p in ipairs(players) do
    table.insert(ChosenGenerals, p.general)
  end
  local generals = Fk:getGeneralsRandomly(8 * n, Fk:getAllGenerals(), ChosenGenerals)
  local skills = {}
  for _, g in ipairs(generals) do
    for _, s in ipairs(g.skills) do
      if not (s.lordSkill or s.switchSkillName or s.frequency > 3 or table.contains(room.onfield_skills, s.name)) then
        table.insertIfNeed(skills, s.name)
      end
    end
  end
  for _, p in ipairs(players) do
    local choices = { "DrawTwo" }
    for i = 1, math.min(3, #skills) do
      table.shuffle(skills)
      table.insert(choices, 1, table.remove(skills, 1))
    end
    p.request_data = json.encode({ choices, choices, "huanhua_choice", "#huanhua-choice:"..p.id, true })
  end

  room:notifyMoveFocus(players, "AskForChoice")
  room:doBroadcastRequest("AskForChoice", players)

  for _, p in ipairs(players) do
    local ChosenSkill
    if p.reply_ready then
      if p.client_reply ~= "DrawTwo"
        then ChosenSkill = p.client_reply
        table.insert(room.onfield_skills, ChosenSkill)
        addSkills(room, p, ChosenSkill)
      else
        p:drawCards(2, "DrawTwo")
      end
    else
      p:drawCards(2, "DrawTwo")
    end
  end
end

  --模式逻辑
local huanhua_getLogic = function()
  local huanhua_logic = GameLogic:subclass("huanhua_logic")

  function huanhua_logic:assignRoles()
    local room = self.room
    local n = #room.players

    for i = 1, n do
      local p = room.players[i]
      p.role = "hidden"
      p.role_shown = true
      room:broadcastProperty(p, "role")
      --p.role = p._splayer:getScreenName() --结算显示更好，但身份图标疯狂报错
    end

    self.start_role = "hidden"
    -- for adjustSeats
    room.players[1].role = "lord"
  end

  --选将
  function huanhua_logic:chooseGenerals()
    local room = self.room
    room.onfield_skills = {}
    local generalNum = room.settings.generalNum
    local lord = room:getLord()
    room.current = lord
    lord.role = self.start_role

    local nonlord = room.players
    self.huanhuaen = nil
    self.huanhuaen = Huanhuaengine:new()
    local generals = Fk:getGeneralsRandomly(#nonlord * generalNum)
    table.shuffle(generals)
    for _, p in ipairs(nonlord) do
      local arg = {}
      for i = 1, generalNum do
        table.insert(arg, table.remove(generals, 1).name)
      end
      p.request_data = json.encode({ arg, 1 })
      p.default_reply = table.random(arg, 1)
    end

    room:doBroadcastNotify("ShowToast", Fk:translate("huanhua_intro"))

    room:notifyMoveFocus(nonlord, "AskForGeneral")
    room:doBroadcastRequest("AskForGeneral", nonlord)

    for _, p in ipairs(nonlord) do
      if p.general == "" and p.reply_ready then
        local generals = json.decode(p.client_reply)
        local general = generals[1]
        room:setPlayerGeneral(p, general, true, true)
      else
        room:setPlayerGeneral(p, p.default_reply[1], true, true)
      end
      p.default_reply = ""
    end

    room:askForChooseKingdom(nonlord)
  end
  --体力初始化
  function huanhua_logic:broadcastGeneral()
    local room = self.room
    local players = room.players
  
    for _, p in ipairs(players) do
      assert(p.general ~= "")
      local general = Fk.generals[p.general]
      p.maxHp = 4
      p.hp = 4
      p.shield = 0
      -- TODO: setup AI here
  
      if p.role ~= "lord" then
        room:broadcastProperty(p, "general")
        room:broadcastProperty(p, "kingdom")
        room:broadcastProperty(p, "deputyGeneral")
      elseif #players >= 5 then
        p.maxHp = p.maxHp + 1
        p.hp = p.hp + 1
      end
      room:broadcastProperty(p, "maxHp")
      room:broadcastProperty(p, "hp")
      room:broadcastProperty(p, "shield")
    end
  end
  --技能初始化
  function huanhua_logic:attachSkillToPlayers()
    local room = self.room
    local players = room.players
    if room.settings.enableDeputy then
    for _, p in ipairs(players) do
      local GetName = function(s)
        return s.name
      end
      local skills = table.map(Fk.generals[p.general].skills, GetName)
      table.insertTableIfNeed(skills, table.map(Fk.generals[p.general].other_skills, GetName))
      p.request_data = json.encode({ skills, skills, "huanhua_remainonlyone", "#huanhua-choice:"..p.id, true })
    end


    room:notifyMoveFocus(players, "AskForChoice")
    room:doBroadcastRequest("AskForChoice", players)

    for _, p in ipairs(players) do
      local ChosenSkill
      if p.reply_ready then
        ChosenSkill = p.client_reply
        addSkills(room, p, ChosenSkill)
      end
    end
  end
  room:doBroadcastNotify("ShowToast", Fk:translate("huanhua_start"))
  end

  return huanhua_logic
end
  --幻化之战
local huanhua_rule = fk.CreateTriggerSkill{
  name = "#huanhua_rule",
  priority = 0.001,
  refresh_events = {fk.GameStart, fk.GameOverJudge, fk.Deathed, fk.RoundStart, fk.RoundEnd},
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    --击杀奖励
    if event == fk.Deathed then
      local body=room:getPlayerById(data.who)
      local logic = room.logic
      local huanhuaen = logic.huanhuaen
      huanhuaen:rewardkill(body,room)
      if data.damage then
        local killer = data.damage.from
        if killer and not killer.dead then
          killer:drawCards(3, "kill")
        end
        if huanhuaen:istokill(killer.id,body,room) then
          huanhuaen:rewardSkills(killer,body,room)

        end
      end
    --轮次开始的幻化
    elseif event == fk.RoundStart then
      room:doBroadcastNotify("ShowToast", Fk:translate("huanhua_start"))
      huanhua_Newskill(room)
    --游戏结束判定
    elseif event == fk.GameOverJudge then
      room:setTag("SkipGameRule", true)
      if #room.alive_players == 1 then
        local winner = Fk.game_modes[room.settings.gameMode]:getWinner(player)
        if winner ~= "" then
          room:gameOver(winner)
          return true
        end
      end
    elseif event == fk.RoundEnd and room:getTag("RoundCount")>3 then
      local players = room.alive_players
      local n=room:getTag("RoundCount")
      if #players == 0 then return false end
      for _, p in ipairs(players) do
        room:notifySkillInvoked(p, "#huanhua__tianjie", "negative")
        room:loseHp(p, n-3, "#huanhua__tianjie")
        room:delay(500)
        room:changeMaxHp(p, 3-n)
        room:delay(500)
      end
    elseif event == fk.GameStart then
      local logic = room.logic
      local huanhuaen = logic.huanhuaen
      huanhuaen:initData(player,data)
      huanhuaen:setkilltarget(room)
    end
  end,
}
Fk:addSkill(huanhua_rule)

--人数限制
local huanhua_mode = fk.CreateGameMode{
  name = "huanhua_mode",
  minPlayer = 2,
  maxPlayer = 10,
  rule = huanhua_rule,
  logic = huanhua_getLogic,
  surrender_func = function(self, playedTime)
    local surrenderJudge = { { text = "#left two alive", passed = #Fk:currentRoom().alive_players == 2 } }
    return surrenderJudge
  end,
  winner_getter = function(self, victim)
    local room = victim.room
    local alive = table.filter(room.alive_players, function(p)
      return not p.surrendered
    end)
    if #alive > 1 then return "" end
    alive[1].role = "renegade" --生草
    return "renegade"
  end,
}

Fk:loadTranslationTable{
  ["huanhua_mode"] = "幻化之战",
  [":huanhua_mode"] = desc_huanhua,
  ["#huanhua_rule"] = "幻化",
  ["#huanhua_choice"] = "为%src选择一个技能获得",
  ["huanhua_choice"] = "幻化",
  ["DrawTwo"] = "摸两张",
  [":DrawTwo"] = "放弃获得技能，摸两张牌",
  ["huanhua_start"] = "幻幻无穷，生生不息",
  ["huanhua_intro"] = "世界的源头，是幻幻",
  ["#left two alive"] = "仅剩两名角色存活",
  ["#huanhua__tianjie"] = "天劫",
}

return huanhua_mode
